var webpack = require('webpack');
var glob = require('glob');
var path = require('path');
var fs = require('fs');
var CopyWebpackPlugin = require('copy-webpack-plugin');

const SOURCE_DIR = 'src/';
const output_path = '../static/resources/views';
var entries = getEntrys(SOURCE_DIR + '*.jsx');

module.exports = {
	//插件项
	plugins: [
		new CopyWebpackPlugin(getCopyfiles(entries.resource))
	],
	//页面入口文件配置
	entry: entries.js,
	//入口文件输出配置
	output: {
		path: path.resolve(__dirname, output_path),
		filename: '[name].js'
	},
	module: {
		//loaders加载器
		loaders: [
			{
				test: /\.(js|jsx)$/,//一个匹配loaders所处理的文件的拓展名的正则表达式，这里用来匹配js和jsx文件（必须）
				loader: 'babel-loader',//loader的名称（必须）
				query: {
					presets: ['es2015', 'react', 'stage-0'] // babel-preset-stage-0 增强es6语法
				}
			}
		]
	}
};

function getEntrys(globPath) {
	var files = glob.sync(globPath);
	var entries = {js: {}, resource: []}, entry, dirname, basename, pathname, extname;
	for (var i = 0; i < files.length; i++) {
		entry = files[i];
		dirname = path.dirname(entry);
		extname = path.extname(entry);
		basename = path.basename(entry, extname);
		var split = dirname.split('/');
		if(extname === '.jsx' || extname === '.js') {
			if(basename !== 'index' && basename !== 'login') {
				continue;
			}
            pathname = path.join(split.slice(2, split.length).join("/"), basename);
			entries.js[pathname] = "./" + entry;
		} else {
            pathname = path.join(split.slice(2, split.length).join("/"), basename + extname);
			entries.resource.push(pathname);
		}
	}
	return entries;
}

function getCopyfiles(resourcs) {
	var copyfiles = [];
	resourcs.forEach(function(pathname){
		var copy_conf = {
			from: SOURCE_DIR + pathname,
			to: pathname
		}
		copyfiles.push(copy_conf);
	});
	return copyfiles;
}

// 获取指定目录下的所有文件（需要制定某个文件类型， 如‘.jsx’）
function readFileList(path, type) {
    var files = fs.readdirSync(path), lastIndex, filesList = [];
    files.forEach(function(file) {
        var stat = fs.statSync(path + file);
        if (stat.isDirectory()) {
            //递归读取文件
            readFileList(path + file + "/", type).forEach(function(item) {
                filesList.push(item);
			});
        } else if((lastIndex = file.lastIndexOf(type)) > 0 && lastIndex === file.length - 4) {
            filesList.push(path + file);
        }
    });
    return filesList;
}
